#!/usr/bin/env python
#-*- coding:utf-8 -*-
from model.get_db import get_db
from model.common import encrypt
from datetime import datetime
from bson import ObjectId

__all__ = ['check_exists', 'check_user', 'check_shell', 'create_user', 'get_user']

db = get_db()


def check_exists(username):
    '''
    判断要创建的用户是否存在
    返回True则表示用户存在
    返回False则表示用户不存在
    '''
    result = db.users.find_one({"username":username})
    if (result):
        r = True
    else:
        r = False

    return r




# 验证用户
def check_user(user, password):
    '''
    用于验证用户的用户名和密码
    返回True则验证正确,返回Flase则验证失败
    '''
    password = encrypt(password)
    passwd = db.users.find_one({"username":user})['password']

    if passwd == password:
        return True
    else:
        return False



# 检验用户验证
def check_shell(user, shell):
    '''
    校验用户验证,shell是密码和用户名加上加密码验证得出
    比较COOKIE里和数据库里的校验是否相同
    user->用户名,必须
    shell-> cookie里的shell,必须
    返回True代表验证成功
    返回False代表验证失败
    '''

    if user and shell:
        # 获取密码
        passwd = db.users.find_one({"username":user})['password']

        # 加密后获取shell
        realshell = encrypt(user + passwd)
        print realshell, shell
        # 比较shell
        if realshell == shell:
            return True
        else:
            return False
    else:
        return False




def create_user(user_dict):
    '''
    user_dict.keys():
    必须:
    username,
    password
    email,
    可选:
    nickname,
    role,
    '''
    if check_exists(user_dict.get('username')):
        return False
    passwd = user_dict.get('password')
    passwd = encrypt(passwd)
    user_dict['password'] = passwd
    user_dict['role'] = user_dict.get('role') if user_dict.get('role', 1) <> 1 else '1'
    user_dict['nickname'] = user_dict.get('nickname') if user_dict.get('nickname', 1) <> 1 else None
    user_dict['date'] = datetime.now()
    r = db.users.insert(user_dict)
    return r



def get_user(_id):
    result = db.user.find_one({"_id":ObjectId(_id)})

    if not result.get('nickname'):
        result['nickname'] = result.get('username')
    return result
